package com.edu.test;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Ioc {

    public static Document load(String filename) {

        Document document = null;

        try {

            SAXReader saxReader = new SAXReader();
            document = saxReader.read(Ioc.class.getClassLoader().getResource(filename)); // 读取XML文件,获得document对象

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return document;

    }

    public static Map<String,Object> iocMap() {

        Document document = load("MyIoc.xml");
        Element rootElement = document.getRootElement();//获取节点根beans
        List<Element> beanList = rootElement.elements();//获取所有bean节点
        Map<String,Object> map = new HashMap<String,Object>();
        Object obj = null;

        try {

            for (int i = 0; i < beanList.size(); i++) {

                Class clazz = Class.forName(beanList.get(i).attribute("class").getValue());//获取bean内的class并放入clazz
                obj = clazz.newInstance();//将clazz对象转换为具体对象
                List<Element> propertyList = beanList.get(i).elements("property");//获取所有property节点
                Field[] fields = clazz.getDeclaredFields();//取得所有clazz对象的属性
                String nameValue = "";

                for (int k = 0; k < propertyList.size(); k++) {

                    for (Field field : fields) {

                        field.setAccessible(true);

                        if (propertyList.get(k).attribute("name").getValue().equals(field.getName())) {

                            nameValue = propertyList.get(k).attribute("value").getValue();//获取xml文件中的property内的名称value属性值
                            Class<?> type = field.getType();//获取该元素的字符类型

                            if (type.equals(int.class)) {

                                field.set(obj, Integer.parseInt(nameValue));

                            } else {

                                field.set(obj, nameValue);

                            }
                        }
                    }
                }

                map.put(beanList.get(i).attribute("id").getValue(),obj);//将对象放入map集合

            }
        } catch (ClassNotFoundException e) {
            System.out.println("未找到该类文件");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            System.out.println("未知路径");
            e.printStackTrace();
        }

        return map;

    }
}
